package omp_remote

import (
	"context"
	"git.mycaigou.com/gfyx/common/cache"
	httpTools "git.mycaigou.com/gfyx/common/http_client"
	"git.mycaigou.com/gfyx/common/simplecopier"
	"git.myscrm.cn/golang/stark/v4"
)

type ompRepository struct {
	Token string `json:"token"`
}

const (
	CreateTenantCallbackUri = "/api/v1/task/execute-result-callback"

	OmpServiceTokenCacheKey              = "gfyx:omp_token_"
	OmpServiceTokenCacheKeyMaxExpireTime = 172800 //172800 两天
)

func NewOmpServiceRepo() OmpServiceRepositoryIface {
	return &ompRepository{}
}

func (r *ompRepository) getUrl(ctx context.Context, uri string) string {
	host := stark.Configer.(stark.ApolloConfigerIface).GetStringValue("omp_service_host", "")
	return host + uri
}

func (r *ompRepository) getToken(ctx context.Context, taskId string) {
	//缓存key
	cacheKey := OmpServiceTokenCacheKey + taskId
	//读缓存
	redisClient, _ := cache.Redis()
	token, err := redisClient.Get(ctx, cacheKey)
	if err != nil {
		stark.Logger.Errorf(ctx, "获取cache失败,key:%s,err:%s", cacheKey, err.Error())
	}
	r.Token = token
	stark.Logger.Infof(ctx, "获取cache,key:%s", cacheKey)
}

func (r *ompRepository) CreateTenantCallback(ctx context.Context, request *CreateTenantCallbackRequest) (*CreateTenantCallbackResponse, error) {
	response := &CreateTenantCallbackResponse{}
	requestMap, _ := simplecopier.StructToMapByJsonTag(request)
	r.getToken(ctx, request.TaskId)
	header := map[string]string{"Authorization": "Bearer " + r.Token}
	_, _, errs := httpTools.New().Post(ctx, r.getUrl(ctx, CreateTenantCallbackUri), requestMap, header).EndStruct(&response)
	if len(errs) > 0 {
		return response, errs[0]
	}

	return response, nil
}
